package com.dragon.pear.modules.trade.common.config;

import com.dragon.common.spring.openapi.ApiGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;

import java.lang.reflect.Method;

public class OpenApiUtil {
    private static final Logger logger = LoggerFactory.getLogger(OpenApiUtil.class);
    
    // 使用 ThreadLocal 存储当前正在处理的方法信息
    private static final ThreadLocal<MethodContext> currentMethodContext = new ThreadLocal<>();

    public static boolean isSupport(HandlerMethod handlerMethod, String group) {
        // 创建方法上下文
        MethodContext context = new MethodContext(handlerMethod, group);
        currentMethodContext.set(context);
        
        try {
            return doIsSupport(handlerMethod, group);
        } finally {
            // 清理 ThreadLocal
            currentMethodContext.remove();
        }
    }
    
    private static boolean doIsSupport(HandlerMethod handlerMethod, String group) {
        Method method = handlerMethod.getMethod();
        Class<?> beanType = handlerMethod.getBeanType();
        
        // 验证上下文一致性
        MethodContext context = currentMethodContext.get();
        if (context != null && !context.matches(handlerMethod, group)) {
            logger.error("🚨 上下文不一致! 期望: {}, 实际: {}", context, 
                new MethodContext(handlerMethod, group));
        }
        
        logger.info("判断类: {}, 方法: {}", beanType.getSimpleName(), method.getName());
        
        String foundGroup = findApiGroupFromClass(beanType);
        boolean result = group.equals(foundGroup);
        
        logger.info("结果 - 类: {}, 期望分组: {}, 实际分组: {}, 匹配: {}", 
            beanType.getSimpleName(), group, foundGroup, result);
        
        return result;
    }

    /**
     * 从类中查找分组标记
     *
     * @param clazz
     * @return
     */
    public static String findApiGroupFromClass(Class<?> clazz) {
        // 优先检查类本身的注解
        if (clazz.isAnnotationPresent(ApiGroup.class)) {
            return clazz.getAnnotation(ApiGroup.class).value();
        }

        // 检查所有接口
        for (Class<?> interfaceClass : clazz.getInterfaces()) {
            if (interfaceClass.isAnnotationPresent(ApiGroup.class)) {
                return interfaceClass.getAnnotation(ApiGroup.class).value();
            }
        }

        // 检查父类
        Class<?> superclass = clazz.getSuperclass();
        if (superclass != null && superclass != Object.class) {
            String superGroup = findApiGroupFromClass(superclass);
            if (superGroup != null) {
                return superGroup;
            }
        }

        return null;
    }
    
    // 方法上下文类
    private static class MethodContext {
        private final HandlerMethod handlerMethod;
        private final String group;
        private final long threadId;
        private final long timestamp;
        
        public MethodContext(HandlerMethod handlerMethod, String group) {
            this.handlerMethod = handlerMethod;
            this.group = group;
            this.threadId = Thread.currentThread().getId();
            this.timestamp = System.currentTimeMillis();
        }
        
        public boolean matches(HandlerMethod otherHandlerMethod, String otherGroup) {
            return this.handlerMethod.equals(otherHandlerMethod) && 
                   this.group.equals(otherGroup) &&
                   this.threadId == Thread.currentThread().getId();
        }
        
        @Override
        public String toString() {
            return String.format("MethodContext{method=%s, group=%s, thread=%d}", 
                handlerMethod.getMethod().getName(), group, threadId);
        }
    }
}